//
//  WDFilePublicAreaLoader.swift
//  Project
//
//  Created by wang on 2021/10/8.
//

import UIKit


class ChatUpPublicAreaLoader: NSObject {
	
	//MARK:数据存储在公共区(公共区的数据在切换用户时不会删除)
	//library + "/larkplayer/Global_Attribute.plist"
	static func store(_ value: Any?, forKey: String, userid: String? = nil) {
		let filePath = ChatUpDBBaseConfiguration.getPublicAreaPlist()
		let publicArea = NSMutableDictionary(contentsOfFile: filePath) ?? [:]
		createDirectory()
		if let userid = userid {
			let user = (publicArea[userid] as? NSMutableDictionary) ?? [:]
			user.setValue(value, forKey: forKey)
			publicArea.setValue(user, forKey: userid)
		} else {
			publicArea.setValue(value, forKey: forKey)
		}
		publicArea.write(toFile: filePath, atomically: true)
	}
	
	//MARK:获取公共区的数据(公共区的数据在切换用户时不会删除)
	static func get(forKey: String, userid: String? = nil) -> Any? {
		let filePath = ChatUpDBBaseConfiguration.getPublicAreaPlist()
		let publicArea = NSMutableDictionary(contentsOfFile: filePath) ?? [:]
		createDirectory()
		if let userid = userid {
			let user = (publicArea[userid] as? NSMutableDictionary) ?? [:]
			if let value = user[forKey] as? String {
				return value
			}
		} else {
			if let value = publicArea[forKey] as? String {
				return value
			}
		}
		return nil
	}
	
	//MARK:获取公共区的数据(公共区的数据在切换用户时不会删除)
	static func getString(forKey: String, userid: String? = nil) -> String? {
		if let obj = get(forKey: forKey, userid: userid) as? String {
			return obj
		}
		return nil
	}
	
	/// 创建文件夹
	static func createDirectory()  {
		if !FileManager.default.fileExists(atPath: ChatUpDBBaseConfiguration.libraryMemePrefix) {
			do {
				try FileManager.default.createDirectory(
					atPath: ChatUpDBBaseConfiguration.libraryMemePrefix,
					withIntermediateDirectories: true, attributes: nil)
			} catch {
				print(error.localizedDescription);
			}
		}
	}
	
}

